package com.study.example.gameserver.module.scene.bt.node;

import com.sparrow.common.ai.behaviortree.BehaviorContext;
import com.sparrow.common.ai.behaviortree.node.impl.ConditionNode;
import com.study.example.gameserver.module.scene.domain.SceneMap;
import com.study.example.gameserver.module.scene.entity.IPlayerEntity;
import com.study.example.gameserver.module.scene.entity.impl.Monster;
import com.study.example.gameserver.module.player.entity.Player;

import java.util.Map;

/**
 * 条件节点：判断怪物是否在最近被攻击过
 */
public class BeAttack extends ConditionNode {

    /** 被攻击的判定时间窗口（毫秒） */
    private static final long ATTACK_INTERVAL = 2000L;

    @Override
    public boolean check(BehaviorContext context) {
        Monster monster = context.getOwner();
        if (monster == null) {
            return false;
        }

        SceneMap sceneMap = context.get("SceneMap", SceneMap.class);
        if (sceneMap == null || monster.getAttackMeIds().isEmpty()) {
            return false;
        }

        long now = System.currentTimeMillis();

        // 遍历最近攻击者
        for (Map.Entry<Long, Long> entry : monster.getAttackMeIds().entrySet()) {
            long attackerId = entry.getKey();
            long lastAttackTime = entry.getValue();

            if (now - lastAttackTime > ATTACK_INTERVAL) {
                continue; // 超时，忽略
            }

            IPlayerEntity playerEntity = sceneMap.getPlayers().get(attackerId);
            if (playerEntity instanceof Player) {
                return true; // 存在有效攻击者
            }
        }

        return false;
    }
}
